package me.mritd.swing;
/**
 *                             _ooOoo_
 *                            o8888888o
 *                            88" . "88
 *                            (| -_- |)
 *                            O\  =  /O
 *                         ____/`---'\____
 *                       .'  \\|     |//  `.
 *                      /  \\|||  :  |||//  \
 *                     /  _||||| -:- |||||-  \
 *                     |   | \\\  -  /// |   |
 *                     | \_|  ''\---/''  |   |
 *                     \  .-\__  `-`  ___/-. /
 *                   ___`. .'  /--.--\  `. . __
 *                ."" '<  `.___\_<|>_/___.'  >'"".
 *               | | :  `- \`.;`\ _ /`;.`/ - ` : | |
 *               \  \ `-.   \_ __\ /__ _/   .-` /  /
 *          ======`-.____`-.___\_____/___.-`____.-'======
 *                             `=---='
 *          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 *                         佛祖保佑        永无BUG
 *              佛曰:  
 *                     写字楼里写字间，写字间里程序员；  
 *                     程序人员写程序，又拿程序换酒钱。  
 *                     酒醒只在网上坐，酒醉还来网下眠；  
 *                     酒醉酒醒日复日，网上网下年复年。  
 *                     但愿老死电脑间，不愿鞠躬老板前；  
 *                     奔驰宝马贵者趣，公交自行程序员。  
 *                     别人笑我忒疯癫，我笑自己命太贱；  
 *                     不见满街漂亮妹，哪个归得程序员？  
 *                     							code by 漠然
*/
import java.awt.AWTException;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.HeadlessException;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ExecutionException;

import javax.imageio.ImageIO;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.SwingWorker;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;

import org.apache.log4j.Logger;
import org.jb2011.lnf.beautyeye.BeautyEyeLNFHelper;
import org.jb2011.lnf.beautyeye.ch3_button.BEButtonUI;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.impl.StdSchedulerFactory;

import me.mritd.email.MailSender;
import me.mritd.quartz.execute.EmailJobExecute;
import me.mritd.util.BareBonesBrowserLaunch;
import me.mritd.util.FileUtil;
import me.mritd.util.ParamUtil;
import me.mritd.util.QuartzStatusListener;
import me.mritd.util.TextAreaLogAppender;
import me.mritd.vo.EmailVo;
import me.mritd.vo.QuartzInfoVo;
/**
 * 
 * Copyright © 2015 Mritd. All rights reserved.
 * @ClassName MailFrame
 * @Description TODO 邮件发送工具主类
 * @author 漠然
 * @date 2015年10月31日 下午5:07:50
 * @version 2.0
 */
public class MailFrame extends JFrame {
	
	private final Logger logger = Logger.getLogger(MailFrame.class);
	public static final String PROPERTIESREMARK = "MailUtil Properties";
	public static final String SYSCONFIGDIR = System.getProperty("user.dir")+File.separator+"mtmp"+File.separator+"config"+File.separator;
	public static final String SYSCONFIGPATH = System.getProperty("user.dir")+File.separator+"mtmp"+File.separator+"config"+File.separator+"mail.properties";
	private static final long serialVersionUID = 725945874902618461L;
	public static String HTMLFILEDIR ;	//存在逻辑不严谨 该变量可被外界破坏
	private JPanel mailPane;
	private JTextField fromNickName;
	private JTextField userName;
	private JTextField mailServerHost;
	private JTextField mailServerPort;
	private JTextField toAddress;
	private JTextField subject;
	private JTextField content;
	private JPasswordField password;
	private JTextArea loginfo;
	private TrayIcon trayIcon;			//托盘图标
	private SystemTray systemTray;		//获得系统托盘的实例 	
	private String subjectValue;
	private PopupMenu pop;
	private final MenuItem exit;
	private final MenuItem show;
	private JScrollPane loginfoScrollPane;
	private JTextField attachments;
	private JLabel quartzStatus;
	private JLabel emailJobStatus;
	private JTextField cron;
	private JMenuItem lockProperties;
	private JMenuItem loadProperties;
	private JMenuItem saveProperties;
	private JMenuItem exitItem;
	private JMenu setting;
	private JMenu about;
	private JMenuItem homePage;
	private JMenuItem blog;
	private JButton sendMail;
	private JButton timingSend;
	private JButton stopTimingSend;
	private JPanel quartzPanel;
	private JLabel labelquartzStatus;
	private JLabel labelemailJobStatus;
	private JLabel labelcron;
	private JFileChooser exportCfgChooser;	//保存配置文件  文件选择器
	private JFileChooser loadCfgChooser;	//加载配置文件  文件选择器
	private JFileChooser htmlDirChooser;	//HTML文件  文件选择器
	private ParamUtil paramUtil = new ParamUtil();
	private FileUtil fileUtil = new FileUtil();
	private static Scheduler scheduler ;

	
	public static void main(String[] args) {
		try{
			BeautyEyeLNFHelper.frameBorderStyle = BeautyEyeLNFHelper.FrameBorderStyle.generalNoTranslucencyShadow;
			UIManager.put("RootPane.setupButtonVisible", false);
			org.jb2011.lnf.beautyeye.BeautyEyeLNFHelper.launchBeautyEyeLNF();
	    }catch(Exception e){
	    	Logger.getLogger(MailFrame.class).error("BeautyEye初始化失败,异常信息: ", e);
	    }
		
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					MailFrame frame = new MailFrame();
					frame.setLocationRelativeTo(null);	//窗口正中央显示
					frame.setVisible(true);				//显示窗口
					frame.init(); 	 					//其他信息初始化
				} catch (Exception e) {
					Logger.getLogger(MailFrame.class).error("异常信息: ", e);
				}
			}
		});
		Logger.getLogger(MailFrame.class).info("++++++ 程序启动!");
	}
	
	/**
	 * 
	 * @Title: init
	 * @Description: TODO 初始化方法
	 * @return: void
	 */
	public void init(){
		try {
			Thread t = new TextAreaLogAppender(loginfo, loginfoScrollPane);
			t.start();
		} catch (IOException e) {
			logger.info("###### 初始化日志组件失败:",e);
		} 
		//初始化配置文件
		initProperties();
		//初始化Quartz调度器
		initQuartzScheduler();
		
		Thread t1 = new QuartzStatusListener(quartzStatus,emailJobStatus);
		t1.start();
	}
	
	/**
	 * 
	 * @Title: initProperties
	 * @Description: TODO 初始化配置文件
	 * @return: void
	 */
	public void initProperties(){
		
		logger.info("###### 初始化配置文件开始!");
		logger.info("###### 初始化配置文件目录: "+SYSCONFIGDIR);
		logger.info("###### 初始化配置文件路径: "+SYSCONFIGPATH);
		new SwingWorker<Boolean, Boolean>() {

			@Override
			protected Boolean doInBackground() throws Exception {
				//默认配置文件位置
				File cfgDir = new File(SYSCONFIGDIR);
				File cfg = new File(SYSCONFIGPATH);
				
				try {
					//如果配置文件存在 则加载配置文件
					if (cfgDir.exists()&&cfg.exists()) {
						loadCfg(SYSCONFIGPATH,true);
					}
					//配置文件目录不存在 则递归创建
					if (!cfgDir.exists()) {
						boolean mkdirs = cfgDir.mkdirs();
						if (mkdirs) logger.info("###### 创建配置文件目录成功!");
						else logger.error("XXXXXX 创建配置文件目录失败!");
					}
					//配置文件不存在则创建
					if (!cfg.exists()) {
						boolean createState = cfg.createNewFile();
						if (createState) logger.info("###### 创建配置文件成功!");
						else logger.error("XXXXXX 创建配置文件失败!");
						boolean saveState = saveCfg(SYSCONFIGPATH);
						if (saveState) logger.info("###### 初始化配置文件信息写入成功!");
						else logger.error("XXXXXX 初始化配置文件信息写入失败!");
					}
					return true;
				} catch (IOException e) {
					logger.error("XXXXXX 初始化配置文件错误!");
					logger.error("错误信息 :",e);
					return false;
				}
			}

			@Override
			protected void process(List<Boolean> chunks) {
				
				try {
					Boolean initState = get();
					if (!initState) {
						JOptionPane.showMessageDialog(mailPane, "初始化配置文件错误!", "错误", JOptionPane.ERROR_MESSAGE);
					}
					super.process(chunks);
					logger.info("###### 初始化配置文件成功!");
				} catch (InterruptedException e) {
					logger.error("XXXXXX 初始化配置文件失败:",e);
				} catch (ExecutionException e) {
					logger.error("XXXXXX 初始化配置文件失败:",e);
				}
			}
		}.execute();
	}
	
	public void initQuartzScheduler(){
		try {
			//创建调度器
			scheduler = new StdSchedulerFactory().getScheduler();
			//启动调度器
			scheduler.start();
		} catch (SchedulerException e) {
			logger.error("XXXXXX 初始化调度器失败: ",e);
		}
	}
	
	/**
	 * 
	 * @Title loadCfg 
	 * @Description TODO 加载指定配置文件
	 * @param cfgPath
	 * @return boolean
	 * @throws
	 */
	private void loadCfg(final String cfgPath,final boolean initFlag){
		new SwingWorker<Properties, Properties>(){
			//加载配置文件信息
			@Override
			protected Properties doInBackground() throws Exception {
				logger.info("###### 加载配置信息到 Frame!");
				return new ParamUtil().loadParam(cfgPath, ParamUtil.LoadPathType.ROOTPATH);
			}
			
			//回写UI界面
			@Override
			protected void done() {
				try {
					Properties loadCfg = get();
					if (loadCfg!=null) {
						logger.info("###### 进行UI回写!");
						mailServerHost.setText(loadCfg.getProperty("mailServerHost"));
						mailServerPort.setText(loadCfg.getProperty("mailServerPort"));
						fromNickName.setText(loadCfg.getProperty("fromNickName"));
						userName.setText(loadCfg.getProperty("userName"));
						password.setText(loadCfg.getProperty("password"));
						toAddress.setText(loadCfg.getProperty("toAddress"));
						subject.setText(loadCfg.getProperty("subject"));
						cron.setText(loadCfg.getProperty("cron"));
						HTMLFILEDIR = loadCfg.getProperty("htmlDir");
						if (HTMLFILEDIR!=null&&!HTMLFILEDIR.trim().equals("")) {
							content.setText(HTMLFILEDIR);
						}else {
							HTMLFILEDIR = "双击选择HTML文件目录";
							content.setText(HTMLFILEDIR);
						}
						logger.info("###### 配置信息加载成功,参数信息 : "+loadCfg.toString());
						if (!initFlag) {
							//非初始化加载  写入本地存储
							saveCfg(SYSCONFIGPATH);
						}
					}
				} catch (InterruptedException e) {
					logger.error("XXXXXX 加载MailUtil配置文件出错:",e);
				} catch (ExecutionException e) {
					logger.error("XXXXXX 加载MailUtil配置文件出错:",e);
				}
				super.done();
			}
			
		}.execute();
		
	}
	
	/**
	 * 
	 * @Title: saveProperties
	 * @Description: TODO 保存当前Swing相关输入框内容到配置文件
	 * @param filePath
	 * @return boolean  
	 * @throws
	 * 2015年10月8日 下午3:11:37
	 */
	private boolean saveCfg(String filePath){
		try {
			//获取所有界面信息
			Map<String,String> data = new HashMap<String, String>();
			data.put("mailServerHost", mailServerHost.getText());
			data.put("mailServerPort", mailServerPort.getText());
			data.put("fromNickName", fromNickName.getText());
			data.put("userName", userName.getText());
			data.put("password", String.valueOf(password.getPassword()));
			data.put("toAddress", toAddress.getText());
			data.put("subject", subject.getText());
			data.put("htmlDir", content.getText());
			data.put("cron", cron.getText());
			if (HTMLFILEDIR==null||HTMLFILEDIR.equals("双击选择HTML文件目录")) {
				data.put("htmlDir", "");
			}else {
				data.put("htmlDir", HTMLFILEDIR);
			}
			paramUtil.writeProperties(data, PROPERTIESREMARK, filePath, ParamUtil.LoadPathType.ROOTPATH);
			return true;
		} catch (FileNotFoundException e) {
			logger.error("XXXXXX 尝试写入配置文件时未找到该文件！");
			logger.error("异常信息: ", e);
			return false;
		} catch (IOException e) {
			logger.error("XXXXXX 尝试写入配置文件时出现I/O异常！");
			logger.error("异常信息: ", e);
			return false;
		}
	}
	
	/**
	 * 
	 * <p>Title: 默认构造方法</p> 
	 * <p>Description: 窗体初始化 及相关组件初始化</p>
	 */
	public MailFrame() {
		setResizable(false);
		//窗口最小化设置
		pop = new PopupMenu();
		show = new MenuItem("打开程序");
		exit = new MenuItem("退出程序");
		pop.add(show);
		pop.add(exit);
		try {
			systemTray = SystemTray.getSystemTray();
			trayIcon = new TrayIcon(ImageIO.read(MailFrame.class.getResourceAsStream("/me/mritd/img/logo.png")),"邮件定时发送工具",pop);
			trayIcon.setImageAutoSize(true);  //必须设置为true 让图盘图标自适应大小
			systemTray.add(trayIcon);
		} catch (IOException e) {
			logger.info("###### 初始化托盘图标I/O失败!");
			logger.error("异常信息: ", e);
		} catch (AWTException e) {
			logger.info("###### 设置托盘图标失败!");
			logger.error("异常信息: ", e);
		}
		
		//监听关闭事件，点击关闭后隐藏进系统托盘
		addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				dispose();
				trayIcon.displayMessage("提示", "程序已经最小化到托盘!",TrayIcon.MessageType.INFO);
			}
		});
		
		//双击后显示
		trayIcon.addMouseListener(
            new MouseAdapter() {
            	public void mouseClicked(MouseEvent e){
            		if (e.getClickCount()==2) {
            			setExtendedState(JFrame.NORMAL);
            			setVisible(true);
					}
                }
			});
		
		// 选项注册事件
		ActionListener al2 = new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				// 退出程序
				if (e.getSource() == exit) {
					logger.info("------ 程序退出!");
					try {
						new StdSchedulerFactory().getScheduler().shutdown();
						logger.info("###### 调度器停止成功!");
					} catch (SchedulerException e1) {
						logger.error("XXXXXX 调度器停止失败: ",e1);
					}
					System.exit(0);// 退出程序
				}
				// 打开程序
				if (e.getSource() == show) {
					setExtendedState(JFrame.NORMAL);// 设置状态为正常
					setVisible(true);
				}
			}
		};
		
		show.addActionListener(al2);
		exit.addActionListener(al2);
		
		setIconImage(Toolkit.getDefaultToolkit().getImage(MailFrame.class.getResource("/me/mritd/img/logo.png")));
		setTitle("邮件发送工具");
		setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		setBounds(100, 100, 934, 647);
		
		JMenuBar menuBar = new JMenuBar();
		setJMenuBar(menuBar);
		
		setting = new JMenu("设置");
		setting.setIcon(new ImageIcon(MailFrame.class.getResource("/me/mritd/img/menu_setting.png")));
		setting.setFont(new Font("华文新魏", Font.PLAIN, 16));
		menuBar.add(setting);
		
		loadProperties = new JMenuItem("加载配置文件");
		loadProperties.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				//初始化文件选择器
				loadCfgChooser = new JFileChooser();
				//设置只能选择文件呢
				loadCfgChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
				//获取用户选择状态
				int fileOpenDialog = loadCfgChooser.showOpenDialog(MailFrame.this);
				if (fileOpenDialog==JFileChooser.APPROVE_OPTION ) {
					logger.info("###### 开始加载Email配置文件!");
					//获取文件选择绝对路径
					final String cfgPath = loadCfgChooser.getSelectedFile().getAbsolutePath();
					//加载配置文件
					loadCfg(cfgPath,false);
					
				}else if (fileOpenDialog==JFileChooser.CANCEL_OPTION) {
					logger.info("###### 用户取消加载配置文件!");
				} else if (fileOpenDialog==JFileChooser.ERROR_OPTION ){
					logger.error("XXXXXX 尝试加载Email配置文件信息出错!");
				}
			}
		});
		
		saveProperties = new JMenuItem("导出配置文件");
		saveProperties.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				logger.info("###### 开始保存MailUtil配置文件!");
				//初始化文件选择器
				exportCfgChooser = new JFileChooser();	
				//设置只能选择文件
				exportCfgChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
				//获取用户选择类型 
				int fileOpenDialog = exportCfgChooser.showOpenDialog(MailFrame.this);
				//用户执行了文件选择
				if (fileOpenDialog==JFileChooser.APPROVE_OPTION ) {
					//获取用户选择的文件绝对路径
					final String savePath = exportCfgChooser.getSelectedFile().getAbsolutePath();
					//调用 SwingWorker 执行后台IO操作
					new SwingWorker<Boolean, Boolean>() {
						@Override
						protected Boolean doInBackground() throws Exception {
							//保存 配置文件操作
							return saveCfg(savePath);
						}

						@Override
						protected void done() {
							try {
								//get方法将自动拿到 doInBackground 返回值，即 保存配置文件是否成功
								if (get()) {
									JOptionPane.showMessageDialog(mailPane, "保存配置文件成功!", "提示", JOptionPane.INFORMATION_MESSAGE);
								}else {
									JOptionPane.showMessageDialog(mailPane, "保存配置文件失败!", "错误", JOptionPane.ERROR_MESSAGE);
								}
							} catch (HeadlessException e) {
								logger.error("XXXXXX 保存配置文件出错:", e);
							} catch (InterruptedException e) {
								logger.error("XXXXXX 保存配置文件出错:", e);
							} catch (ExecutionException e) {
								logger.error("XXXXXX 保存配置文件出错:", e);
							}
							super.done();
						}
					}.execute();
					logger.info("###### 保存MailUtil配置文件完成!");
				}else if (fileOpenDialog==JFileChooser.CANCEL_OPTION) {
					logger.info("###### 用户取消导出配置文件!");
				} else if (fileOpenDialog==JFileChooser.ERROR_OPTION ){
					logger.error("XXXXXX 尝试导出Email配置文件信息出错!");
				}
				
				
			}
		});
		saveProperties.setIcon(new ImageIcon(MailFrame.class.getResource("/me/mritd/img/menu_saveproperties.png")));
		saveProperties.setFont(new Font("华文新魏", Font.PLAIN, 14));
		setting.add(saveProperties);
		loadProperties.setIcon(new ImageIcon(MailFrame.class.getResource("/me/mritd/img/menu_loadfile.png")));
		loadProperties.setFont(new Font("华文新魏", Font.PLAIN, 14));
		setting.add(loadProperties);
		
		lockProperties = new JMenuItem("锁定配置文件");
		lockProperties.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if(lockProperties.getText().equals("锁定配置文件")){
					lockProperties.setText("解锁配置文件");
					lockProperties.setIcon(new ImageIcon(MailFrame.class.getResource("/me/mritd/img/menu_unlock.png")));
					mailServerHost.setEnabled(false);
					mailServerPort.setEnabled(false);
					fromNickName.setEnabled(false);
					userName.setEnabled(false);
					password.setEnabled(false);
					toAddress.setEnabled(false);
					userName.setEnabled(false);
					subject.setEnabled(false);
					cron.setEnabled(false);
				}else {
					lockProperties.setText("锁定配置文件");
					lockProperties.setIcon(new ImageIcon(MailFrame.class.getResource("/me/mritd/img/menu_lock.png")));
					mailServerHost.setEnabled(true);
					mailServerPort.setEnabled(true);
					fromNickName.setEnabled(true);
					userName.setEnabled(true);
					password.setEnabled(true);
					toAddress.setEnabled(true);
					userName.setEnabled(true);
					subject.setEnabled(true);
					cron.setEnabled(true);
				}
			}
		});
		lockProperties.setIcon(new ImageIcon(MailFrame.class.getResource("/me/mritd/img/menu_lock.png")));
		lockProperties.setFont(new Font("华文新魏", Font.PLAIN, 14));
		setting.add(lockProperties);
		
		exitItem = new JMenuItem("退出");
		exitItem.setIcon(new ImageIcon(MailFrame.class.getResource("/me/mritd/img/menu_exit.png")));
		exitItem.setFont(new Font("华文新魏", Font.PLAIN, 14));
		exitItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				logger.info("###### 用户从设置选择退出程序!");
				try {
					new StdSchedulerFactory().getScheduler().shutdown();
					logger.info("###### 调度器停止成功!");
				} catch (SchedulerException e1) {
					logger.error("XXXXXX 调度器停止失败: ",e1);
				}
				logger.info("------ 程序退出!");
				System.exit(0);
			}
		});
		setting.add(exitItem);
		
		about = new JMenu("关于");
		about.setIcon(new ImageIcon(MailFrame.class.getResource("/me/mritd/img/menu_about.png")));
		about.setFont(new Font("华文新魏", Font.PLAIN, 16));
		menuBar.add(about);
		
		homePage = new JMenuItem("项目主页");
		homePage.setIcon(new ImageIcon(MailFrame.class.getResource("/me/mritd/img/menu_homepage.png")));
		homePage.setFont(new Font("华文新魏", Font.PLAIN, 14));
		homePage.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				BareBonesBrowserLaunch.openURL("http://git.oschina.net/D.k/MailUtil");
			}
		});
		
		about.add(homePage);
		blog = new JMenuItem("个人博客");
		blog.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				BareBonesBrowserLaunch.openURL("http://mritd.me");
			}
		});
		
		blog.setIcon(new ImageIcon(MailFrame.class.getResource("/me/mritd/img/menu_blog.png")));
		blog.setFont(new Font("华文新魏", Font.PLAIN, 14));
		about.add(blog);
		mailPane = new JPanel();
		mailPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(mailPane);
		JLabel labeluserName = new JLabel("发件人邮箱地址 : ");
		labeluserName.setFont(new Font("华文新魏", Font.PLAIN, 16));
		
		JLabel labeltoAddress = new JLabel("收件人邮箱地址 : ");
		labeltoAddress.setToolTipText("");
		labeltoAddress.setFont(new Font("华文新魏", Font.PLAIN, 16));
		
		JLabel labelpassword = new JLabel("发件人邮箱密码 : ");
		labelpassword.setFont(new Font("华文新魏", Font.PLAIN, 16));
		
		JLabel labelmailServerHost = new JLabel("发件服务器 : ");
		labelmailServerHost.setFont(new Font("华文新魏", Font.PLAIN, 16));
		
		JLabel labelmailServerPort = new JLabel("发件服务器端口 : ");
		labelmailServerPort.setFont(new Font("华文新魏", Font.PLAIN, 16));
		
		JLabel labelsubject = new JLabel("邮件主题 : ");
		labelsubject.setFont(new Font("华文新魏", Font.PLAIN, 16));
		
		JLabel labelfromNickName = new JLabel("发件人昵称 : ");
		labelfromNickName.setFont(new Font("华文新魏", Font.PLAIN, 16));
		
		JLabel labelcontent = new JLabel("邮件HTML目录 : ");
		labelcontent.setFont(new Font("华文新魏", Font.PLAIN, 16));
		
		JLabel labelattachments = new JLabel("附件 : ");
		labelattachments.setFont(new Font("华文新魏", Font.PLAIN, 16));
		
		fromNickName = new JTextField();
		fromNickName.setColumns(10);
		
		userName = new JTextField();
		userName.setColumns(10);
		
		mailServerHost = new JTextField();
		mailServerHost.setColumns(10);
		
		mailServerPort = new JTextField();
		mailServerPort.setColumns(10);
		
		toAddress = new JTextField();
		toAddress.setToolTipText("多人请用英文逗号隔开");
		toAddress.setColumns(10);
		
		subject = new JTextField();
		subject.setColumns(10);
		
		content = new JTextField();
		content.setToolTipText("双击选择HTML文件目录");
		content.setText("双击选择HTML文件目录");
		content.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				if (e.getClickCount() == 2) {
					logger.info("###### 选择HTML目录!");
					//初始化文件选择器
					htmlDirChooser = new JFileChooser();
					//设置只能选择目录
					htmlDirChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
					//显示文件选择器 并获取用户选择类型 
					int fileOpenDialog = htmlDirChooser.showOpenDialog(MailFrame.this);
					//用户执行了文件选择
					if (fileOpenDialog==JFileChooser.APPROVE_OPTION ) {
						//获取用户选择的文件绝对路径
						final String htmlPath = htmlDirChooser.getSelectedFile().getAbsolutePath();
						//设置content
						content.setText(htmlPath);
						HTMLFILEDIR = htmlPath;
						logger.info("###### 设置HTML文件夹为: "+htmlPath);
					}else if (fileOpenDialog==JFileChooser.CANCEL_OPTION) {
						logger.info("###### 用户取消设置HTML文件夹!");
					} else if (fileOpenDialog==JFileChooser.ERROR_OPTION ){
						logger.error("XXXXXX 尝试设置HTML文件夹出错!");
					}
			    }
			}
		});
		content.setEnabled(false);
		content.setColumns(10);
		
		password = new JPasswordField();
		
		JLabel labelloginfo = new JLabel("日志信息 : ");
		labelloginfo.setFont(new Font("华文新魏", Font.PLAIN, 16));
		
		sendMail = new JButton("发送");
		sendMail.setFont(new Font("华文新魏", Font.PLAIN, 16));
		sendMail.setIcon(null);
		sendMail.setUI(new BEButtonUI().setNormalColor(BEButtonUI.NormalColor.green));
		sendMail.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				new SwingWorker<Boolean, Boolean>(){

					@Override
					protected Boolean doInBackground() throws Exception {
						logger.info("@@@@@@ 开始发送邮件!");
						try {	//整操作try-catch 不关心错误信息 因为其错误可在日志中查看 
							//获取邮件相关信息
							EmailVo mailInfo = getMailInfo();
							if (mailInfo!=null){
								if (HTMLFILEDIR==null||HTMLFILEDIR.equals("双击选择HTML文件目录")) {
									logger.error("XXXXXX 未选择HTML目录!");
									publish(false);
									return false;
								}
								//获取HTML目录文件
								ArrayList<File> fileList = fileUtil.getListFiles(HTMLFILEDIR);
								if (fileList==null||fileList.size()==0) {
									logger.error("XXXXXX 获取HTML文件列表失败!");
									publish(false);
									return false;
								}
								//获取指定目录最后修改文件
								File lastModifyFile = fileUtil.getLastModifyFile(fileList);
								if (lastModifyFile==null) {
									logger.error("XXXXXX 获取最后修改的HTML文件失败!");
									publish(false);
									return false;
								}
								if (!lastModifyFile.getName().endsWith(".html")) {
									logger.error("XXXXXX 最后修改文件并非HTML文件!");
									publish(false);
									return false;
								}
								//获取文件内容
								String contentVlaue = fileUtil.readFileByLines(lastModifyFile);
								mailInfo.setContent(contentVlaue);
								//更新邮件主题为文件名
								subjectValue = lastModifyFile.getName().substring(0,lastModifyFile.getName().indexOf(".html"));
								mailInfo.setSubject(subjectValue);
								//进行发送邮件操作 分批次发送
								boolean sendHtmlMail = false;
								//准备分批次发送
								String allAddr = mailInfo.getToAddress();
								String allAddrArray[] = mailInfo.getToAddress().split(",");
								
								if (allAddrArray.length>20) {	//超过20人则分批发送
									//缓存Email地址
									StringBuffer tempAddr = new StringBuffer();	
									//发送批次
									int level = 1;	
									//遍历所有Email地址
									for (int i = 0; i < allAddrArray.length; i++){
										tempAddr.append(allAddrArray[i]);
										tempAddr.append(",");
										if (i!=0&&i%20==0) {
											logger.info("###### 第["+level+"]批邮件发送地址:"+tempAddr);
											mailInfo.setToAddress(tempAddr.toString());
											sendHtmlMail = new MailSender().sendHtmlMail(mailInfo);
											logger.info("###### 准备线程休眠40s,防止被 kill......");
											Thread.sleep(40000);
											//发送失败则立即终止 可从日志中查找未发送邮件的地址
											if (!sendHtmlMail) break;
											//清空缓存邮件地址
											tempAddr.setLength(0); 	
											level++;
										}else if (i==allAddrArray.length-1) {	//最后一批
											logger.info("###### 最后一批邮件发送地址:"+tempAddr);
											mailInfo.setToAddress(tempAddr.toString());
											sendHtmlMail = new MailSender().sendHtmlMail(mailInfo);
											if (!sendHtmlMail) break;
										}
									}
									
								}else {
									mailInfo.setToAddress(allAddr);
									sendHtmlMail = new MailSender().sendHtmlMail(mailInfo);
									if (sendHtmlMail) logger.info("###### 单次邮件发送成功!");
								}
								
							}else {
								publish(false);
								return false;
							}
							
						} catch (Exception e) {
							logger.error("##### 邮件发送出现错误:", e);
							publish(false);
							return false;
						}
						publish(true);
						return true;
					}

					@Override
					protected void process(List<Boolean> chunks) {
						if (chunks!=null&&!chunks.get(0)) {
							JOptionPane.showMessageDialog(mailPane, "邮件发送失败,请查看日志!", "错误", JOptionPane.ERROR_MESSAGE);
						}else if (chunks!=null&&chunks.get(0)) {
							JOptionPane.showMessageDialog(mailPane, "邮件发送成功!", "提示", JOptionPane.INFORMATION_MESSAGE);
							logger.info("@@@@@@ 邮件发送成功!");
						}
						super.process(chunks);
					}
					
				}.execute();
				
			}
		});

		
		
		timingSend = new JButton("启动定时发送");
		timingSend.setFont(new Font("华文新魏", Font.PLAIN, 16));
		timingSend.setUI(new BEButtonUI().setNormalColor(BEButtonUI.NormalColor.lightBlue));
		timingSend.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				logger.info("@@@@@@ 开始启动定时邮件任务!");
				
				new SwingWorker<Boolean, Boolean>() {

					@Override
					protected Boolean doInBackground() throws Exception {
						try {
							//获取邮件相关信息
							EmailVo mailInfo = getMailInfo();
							//获取调度器JOB相关信息
							QuartzInfoVo quartzInfo = getQuartzInfo();
							
							if (mailInfo==null) {
								logger.error("XXXXXX 邮件相关信息获取失败!");
								publish(false);
								return false;
							}
							
							if (quartzInfo.getCron()==null||quartzInfo.getCron().trim().equals("")) {
								logger.error("XXXXXX Cron表达式为空,禁止启动任务!");
								publish(false);
								return false;
							}
							//更新邮件主题  后面回写UI
							subjectValue = "邮件主题自动设置!";
							
							EmailJobExecute emailJobExecute = new EmailJobExecute();
							emailJobExecute.setTrayIcon(trayIcon);
							boolean startSendEmail = emailJobExecute.startSendEmail(quartzInfo, mailInfo);
							
							if (startSendEmail) {
								logger.info("###### 启动定时邮件任务成功!");
								publish(true);
								return true;
							}else {
								logger.error("XXXXXX 启动定时邮件任务失败!");
								publish(false);
								return false;
							}
						} catch (Exception e) {
							logger.error("XXXXXX 启动定时邮件任务失败: ",e);
							publish(false);
							return false;
						}
					}

					@Override
					protected void process(List<Boolean> chunks) {
						super.process(chunks);
						if (!chunks.get(0)) {
							JOptionPane.showMessageDialog(mailPane, "启动定时邮件任务失败!", "错误", JOptionPane.ERROR_MESSAGE);
						}else {
							//回写UI 更新邮件主题
							subject.setText(subjectValue);
							JOptionPane.showMessageDialog(mailPane, "启动定时邮件任务成功!", "提示", JOptionPane.INFORMATION_MESSAGE);
						}
					}
					
					
				}.execute();;
				
//				new SwingWorker<HashMap<String, Boolean>, HashMap<String, Boolean>>() {
//
//					@Override
//					protected HashMap<String, Boolean> doInBackground()
//							throws Exception {
//						//用于保存邮件发送过程中的状态信息
//						HashMap<String, Boolean> sendDetail = new HashMap<String, Boolean>();
//						//创建邮件发送信息  默认返回的mailinfo中主题和内容为空，发送前由Listener更新
//						Email mailInfo = getMailInfo();
//						if (mailInfo==null) {
//							sendDetail.put("getMailInfo", false);
//						}else {
//							sendDetail.put("getMailInfo", true);
//							//更新邮件主题  后面回写UI
//							subjectValue = "邮件主题自动设置!";
//							EmailJobExecute emailJobExecute = new EmailJobExecute();
//							emailJobExecute.setMailInfo(mailInfo);
//							//托盘图标传入，每次发送成功后托盘提示
//							emailJobExecute.setTrayIcon(trayIcon);
//							//邮件监听器每次执行邮件Job前更新ftp缓存目录,将当前FTP信息传入
//							HashMap<String, String> ftpDetail = new HashMap<String, String>();
//							//给定Quartz触发器触发规则,并执行发送任务
//							boolean startSendEmail = emailJobExecute.startSendEmail(cron.getText());
//							if (startSendEmail) {
//								logger.info("###### 定邮件任务启动成功!");
//							}else{
//								logger.error("XXXXXX 定邮件任务启动失败!");
//							}
//							sendDetail.put("startSendEmail", startSendEmail);
//				
//						}
//						return sendDetail;
//					}
//
//					@Override
//					protected void done() {
//						try {
//							HashMap<String, Boolean> sendDetail = get();
//							if (sendDetail.get("getMailInfo")!=null&&sendDetail.get("getMailInfo")==false) {
//								JOptionPane.showMessageDialog(mailPane, "mailInfo为空，邮件信息缺失!", "错误", JOptionPane.ERROR_MESSAGE);
//							}
//							if (sendDetail.get("startSendEmail")!=null&&sendDetail.get("startSendEmail")==false) {
//								JOptionPane.showMessageDialog(mailPane, "启动定时邮件任务失败!", "错误", JOptionPane.ERROR_MESSAGE);
//							}else if (sendDetail.get("startSendEmail")!=null&&sendDetail.get("startSendEmail")==true) {
//								JOptionPane.showMessageDialog(mailPane, "启动定时邮件任务成功!", "提示", JOptionPane.INFORMATION_MESSAGE);
//							}
//							//回写UI 更新邮件主题
//							subject.setText(subjectValue);
//							super.done();
//						} catch (HeadlessException e) {
//							logger.error("XXXXXX 邮件发送出现错误!", e);
//						} catch (InterruptedException e) {
//							logger.error("XXXXXX 邮件发送出现错误!", e);
//						} catch (ExecutionException e) {
//							logger.error("XXXXXX 邮件发送出现错误!", e);
//						}
//					}
//					
//				}.execute();
					
			}
		});
		
		stopTimingSend = new JButton("停止定时发送");
		stopTimingSend.setFont(new Font("华文新魏", Font.PLAIN, 16));
		stopTimingSend.setUI(new BEButtonUI().setNormalColor(BEButtonUI.NormalColor.red));
		stopTimingSend.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				logger.info("###### 停止定时邮件任务!");
				boolean stopSendEmail = new EmailJobExecute().stopSendEmail();
				if (stopSendEmail){
					logger.info("###### 停止定时邮件任务成功!");
					JOptionPane.showMessageDialog(mailPane, "停止定时邮件任务成功!", "提示", JOptionPane.WARNING_MESSAGE);
				}else{
					logger.info("###### 停止定时邮件任务失败!");
					JOptionPane.showMessageDialog(mailPane, "停止定时邮件任务失败!", "错误", JOptionPane.ERROR_MESSAGE);
				}
				
			}
		});
		
		loginfoScrollPane = new JScrollPane();
		
		attachments = new JTextField();
		attachments.setEnabled(false);
		attachments.setToolTipText("双击选择附件目录");
		attachments.setText("暂不支持");
		attachments.setColumns(10);
		
		JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP);
		tabbedPane.setFont(new Font("华文新魏", Font.PLAIN, 16));
		GroupLayout gl_mailPane = new GroupLayout(mailPane);
		gl_mailPane.setHorizontalGroup(
			gl_mailPane.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_mailPane.createSequentialGroup()
					.addGap(32)
					.addGroup(gl_mailPane.createParallelGroup(Alignment.LEADING, false)
						.addGroup(gl_mailPane.createSequentialGroup()
							.addComponent(sendMail, GroupLayout.PREFERRED_SIZE, 68, GroupLayout.PREFERRED_SIZE)
							.addPreferredGap(ComponentPlacement.UNRELATED)
							.addComponent(timingSend)
							.addPreferredGap(ComponentPlacement.UNRELATED)
							.addComponent(stopTimingSend, GroupLayout.PREFERRED_SIZE, 137, GroupLayout.PREFERRED_SIZE))
						.addGroup(gl_mailPane.createParallelGroup(Alignment.TRAILING)
							.addGroup(gl_mailPane.createSequentialGroup()
								.addGroup(gl_mailPane.createParallelGroup(Alignment.LEADING)
									.addComponent(labelattachments, GroupLayout.PREFERRED_SIZE, 125, GroupLayout.PREFERRED_SIZE)
									.addGroup(Alignment.TRAILING, gl_mailPane.createSequentialGroup()
										.addGroup(gl_mailPane.createParallelGroup(Alignment.TRAILING, false)
											.addComponent(labelsubject, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
											.addComponent(labelcontent, Alignment.LEADING, GroupLayout.DEFAULT_SIZE, 125, Short.MAX_VALUE))
										.addPreferredGap(ComponentPlacement.RELATED)
										.addGroup(gl_mailPane.createParallelGroup(Alignment.LEADING)
											.addComponent(subject, GroupLayout.DEFAULT_SIZE, 191, Short.MAX_VALUE)
											.addComponent(attachments)
											.addComponent(content, GroupLayout.DEFAULT_SIZE, 136, Short.MAX_VALUE)))
									.addGroup(gl_mailPane.createSequentialGroup()
										.addGroup(gl_mailPane.createParallelGroup(Alignment.LEADING, false)
											.addComponent(labelfromNickName, GroupLayout.DEFAULT_SIZE, 125, Short.MAX_VALUE)
											.addComponent(labelpassword, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
											.addComponent(labelmailServerHost, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
											.addComponent(labelmailServerPort, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
											.addComponent(labeltoAddress, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
											.addComponent(labeluserName, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
										.addPreferredGap(ComponentPlacement.RELATED)
										.addGroup(gl_mailPane.createParallelGroup(Alignment.LEADING, false)
											.addComponent(toAddress, GroupLayout.DEFAULT_SIZE, 136, Short.MAX_VALUE)
											.addComponent(mailServerPort, GroupLayout.DEFAULT_SIZE, 136, Short.MAX_VALUE)
											.addComponent(mailServerHost, GroupLayout.DEFAULT_SIZE, 136, Short.MAX_VALUE)
											.addComponent(userName, GroupLayout.DEFAULT_SIZE, 136, Short.MAX_VALUE)
											.addComponent(password)
											.addComponent(fromNickName, GroupLayout.PREFERRED_SIZE, 191, GroupLayout.PREFERRED_SIZE))))
								.addGap(52)
								.addComponent(tabbedPane, GroupLayout.PREFERRED_SIZE, 400, GroupLayout.PREFERRED_SIZE))
							.addGroup(Alignment.LEADING, gl_mailPane.createSequentialGroup()
								.addComponent(labelloginfo, GroupLayout.PREFERRED_SIZE, 125, GroupLayout.PREFERRED_SIZE)
								.addPreferredGap(ComponentPlacement.RELATED)
								.addComponent(loginfoScrollPane, GroupLayout.PREFERRED_SIZE, 643, GroupLayout.PREFERRED_SIZE))))
					.addGap(257))
		);
		gl_mailPane.setVerticalGroup(
			gl_mailPane.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_mailPane.createSequentialGroup()
					.addGap(37)
					.addGroup(gl_mailPane.createParallelGroup(Alignment.LEADING)
						.addGroup(gl_mailPane.createSequentialGroup()
							.addGroup(gl_mailPane.createParallelGroup(Alignment.BASELINE)
								.addComponent(labelfromNickName, GroupLayout.PREFERRED_SIZE, 22, GroupLayout.PREFERRED_SIZE)
								.addComponent(fromNickName, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
							.addPreferredGap(ComponentPlacement.RELATED)
							.addGroup(gl_mailPane.createParallelGroup(Alignment.BASELINE)
								.addComponent(labeluserName, GroupLayout.PREFERRED_SIZE, 22, GroupLayout.PREFERRED_SIZE)
								.addComponent(userName, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
							.addPreferredGap(ComponentPlacement.RELATED)
							.addGroup(gl_mailPane.createParallelGroup(Alignment.BASELINE)
								.addComponent(labelpassword, GroupLayout.PREFERRED_SIZE, 22, GroupLayout.PREFERRED_SIZE)
								.addComponent(password, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
							.addPreferredGap(ComponentPlacement.RELATED)
							.addGroup(gl_mailPane.createParallelGroup(Alignment.BASELINE)
								.addComponent(labelmailServerHost, GroupLayout.PREFERRED_SIZE, 22, GroupLayout.PREFERRED_SIZE)
								.addComponent(mailServerHost, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
							.addPreferredGap(ComponentPlacement.RELATED)
							.addGroup(gl_mailPane.createParallelGroup(Alignment.BASELINE)
								.addComponent(labelmailServerPort, GroupLayout.PREFERRED_SIZE, 22, GroupLayout.PREFERRED_SIZE)
								.addComponent(mailServerPort, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
							.addPreferredGap(ComponentPlacement.RELATED)
							.addGroup(gl_mailPane.createParallelGroup(Alignment.BASELINE)
								.addComponent(labeltoAddress)
								.addComponent(toAddress, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
							.addGap(18)
							.addGroup(gl_mailPane.createParallelGroup(Alignment.BASELINE)
								.addComponent(labelsubject, GroupLayout.PREFERRED_SIZE, 22, GroupLayout.PREFERRED_SIZE)
								.addComponent(subject, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
							.addPreferredGap(ComponentPlacement.RELATED)
							.addGroup(gl_mailPane.createParallelGroup(Alignment.BASELINE)
								.addComponent(labelcontent, GroupLayout.PREFERRED_SIZE, 22, GroupLayout.PREFERRED_SIZE)
								.addComponent(content, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
							.addPreferredGap(ComponentPlacement.RELATED)
							.addGroup(gl_mailPane.createParallelGroup(Alignment.BASELINE)
								.addComponent(labelattachments, GroupLayout.PREFERRED_SIZE, 22, GroupLayout.PREFERRED_SIZE)
								.addComponent(attachments, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)))
						.addComponent(tabbedPane, GroupLayout.PREFERRED_SIZE, 261, GroupLayout.PREFERRED_SIZE))
					.addPreferredGap(ComponentPlacement.RELATED)
					.addGroup(gl_mailPane.createParallelGroup(Alignment.LEADING)
						.addComponent(labelloginfo, GroupLayout.PREFERRED_SIZE, 22, GroupLayout.PREFERRED_SIZE)
						.addComponent(loginfoScrollPane, GroupLayout.DEFAULT_SIZE, 207, Short.MAX_VALUE))
					.addGap(18)
					.addGroup(gl_mailPane.createParallelGroup(Alignment.BASELINE)
						.addComponent(sendMail)
						.addComponent(timingSend)
						.addComponent(stopTimingSend))
					.addGap(34))
		);
		
		quartzPanel = new JPanel();
		tabbedPane.addTab("Quartz设置", null, quartzPanel, null);
		
		labelquartzStatus = new JLabel("Quartz调度器状态 : ");
		labelquartzStatus.setFont(new Font("华文新魏", Font.PLAIN, 16));
		
		quartzStatus = new JLabel("已停止");
		quartzStatus.setIcon(new ImageIcon(MailFrame.class.getResource("/me/mritd/img/menu_stop.png")));
		quartzStatus.setFont(new Font("华文新魏", Font.PLAIN, 14));
		
		labelemailJobStatus = new JLabel("邮件任务执行状态 : ");
		labelemailJobStatus.setFont(new Font("华文新魏", Font.PLAIN, 16));
		
		emailJobStatus = new JLabel("已停止");
		emailJobStatus.setIcon(new ImageIcon(MailFrame.class.getResource("/me/mritd/img/menu_stop.png")));
		emailJobStatus.setFont(new Font("华文新魏", Font.PLAIN, 14));
		
		labelcron = new JLabel("CRON : ");
		labelcron.setFont(new Font("华文新魏", Font.PLAIN, 16));
		
		cron = new JTextField();
		cron.setColumns(10);
		GroupLayout gl_quartzPanel = new GroupLayout(quartzPanel);
		gl_quartzPanel.setHorizontalGroup(
			gl_quartzPanel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_quartzPanel.createSequentialGroup()
					.addGap(23)
					.addGroup(gl_quartzPanel.createParallelGroup(Alignment.LEADING)
						.addGroup(gl_quartzPanel.createSequentialGroup()
							.addComponent(labelcron, GroupLayout.PREFERRED_SIZE, 69, GroupLayout.PREFERRED_SIZE)
							.addPreferredGap(ComponentPlacement.RELATED)
							.addComponent(cron, GroupLayout.PREFERRED_SIZE, 136, GroupLayout.PREFERRED_SIZE))
						.addGroup(gl_quartzPanel.createSequentialGroup()
							.addComponent(labelemailJobStatus)
							.addPreferredGap(ComponentPlacement.UNRELATED)
							.addComponent(emailJobStatus))
						.addGroup(gl_quartzPanel.createSequentialGroup()
							.addComponent(labelquartzStatus)
							.addPreferredGap(ComponentPlacement.UNRELATED)
							.addComponent(quartzStatus, GroupLayout.PREFERRED_SIZE, 568, GroupLayout.PREFERRED_SIZE)))
					.addContainerGap(GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
		);
		gl_quartzPanel.setVerticalGroup(
			gl_quartzPanel.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_quartzPanel.createSequentialGroup()
					.addContainerGap()
					.addGroup(gl_quartzPanel.createParallelGroup(Alignment.BASELINE)
						.addComponent(labelquartzStatus, GroupLayout.PREFERRED_SIZE, 22, GroupLayout.PREFERRED_SIZE)
						.addComponent(quartzStatus))
					.addPreferredGap(ComponentPlacement.UNRELATED)
					.addGroup(gl_quartzPanel.createParallelGroup(Alignment.TRAILING)
						.addComponent(labelemailJobStatus, GroupLayout.PREFERRED_SIZE, 22, GroupLayout.PREFERRED_SIZE)
						.addComponent(emailJobStatus))
					.addPreferredGap(ComponentPlacement.UNRELATED)
					.addGroup(gl_quartzPanel.createParallelGroup(Alignment.BASELINE)
						.addComponent(labelcron, GroupLayout.PREFERRED_SIZE, 22, GroupLayout.PREFERRED_SIZE)
						.addComponent(cron, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
					.addContainerGap(128, Short.MAX_VALUE))
		);
		quartzPanel.setLayout(gl_quartzPanel);
		
		loginfo = new JTextArea();
		loginfoScrollPane.setViewportView(loginfo);
		mailPane.setLayout(gl_mailPane);
	}
	
	/**
	 * 
	 * @Title getMailInfo 
	 * @Description TODO 获取swing界面相关信息封装进邮件类
	 * @return Email 邮件信息
	 * @throws
	 */
	private EmailVo getMailInfo(){
		
		try {
			// return SwingWorker.get() 
			SwingWorker<EmailVo,Boolean> swingWorker = new SwingWorker<EmailVo,Boolean>() {
	
				@Override
				protected EmailVo doInBackground() throws Exception {
					//邮件信息返回结果
					EmailVo mailInfo = new EmailVo();
					//判断界面必要元素是否为空
					if(fromNickName.getText()==null||fromNickName.getText().trim().equals("")||
							mailServerHost.getText()==null||mailServerHost.getText().trim().equals("")||
							mailServerPort.getText()==null||mailServerPort.getText().trim().equals("")||
							password.getPassword()==null||String.valueOf(password.getPassword()).trim().equals("")||
							//不验证邮件主题 发送时自动设置
	//						subject.getText()==null||subject.getText().trim().equals("")||
							toAddress.getText()==null||toAddress.getText().trim().equals("")||
							userName.getText()==null||userName.getText().trim().equals("")){
						
						logger.error("XXXXXX 缺少邮件相关信息，无法启动发送任务!");
						//错误结果 publish 到 process
						publish(false);
						mailInfo = null;
					}else {
						//获取界面信息 赋值
						mailInfo.setMailServerHost(mailServerHost.getText());
						mailInfo.setMailServerPort(mailServerPort.getText());
						mailInfo.setValidate(true);
						mailInfo.setFromNickName(fromNickName.getText());
						mailInfo.setUserName(userName.getText()); 
						mailInfo.setPassword(String.valueOf(password.getPassword()));
						mailInfo.setFromAddress(userName.getText()); 
						mailInfo.setToAddress(toAddress.getText()); 
						mailInfo.setSubject(subject.getText());
						mailInfo.setHtmlDir(HTMLFILEDIR);
					}
					
					return mailInfo;
				}
	
				@Override
				protected void process(List<Boolean> chunks) {
					super.process(chunks);
					if (chunks!=null&&!chunks.get(0)) {
						JOptionPane.showMessageDialog(mailPane, "缺少邮件相关信息，无法启动发送任务!", "邮件信息缺失", JOptionPane.WARNING_MESSAGE);
					}
				}
			};
			swingWorker.execute();
			return 	swingWorker.get();
		} catch (InterruptedException e) {
			logger.info("###### 获取mailinfo出错:",e);
			return null;
		} catch (ExecutionException e) {
			logger.info("###### 获取mailinfo出错:",e);
			return null;
		}
	}
	
	/**
	 * 
	 * @Title getQuartzInfo
	 * @Description TODO 获取调度器相关信息
	 * @return QuartzInfoVo
	 */
	private QuartzInfoVo getQuartzInfo(){
		QuartzInfoVo quartzInfo = new QuartzInfoVo(cron.getText(), "SendEmailJob", "DailyGroup", "SendEmailTrigger", "DailyGroup");
		quartzInfo.setCron(cron.getText());
		return quartzInfo;
	}

}
